package nancal.mp.web.me



import nancal.mp.db.mongo.UserPartnerTypeEnum
import nancal.mp.db.mongo.base.wx.OpenIdNameUrl
import nancal.mp.db.mongo.entity.wx.WxAppUser
import nancal.mp.db.mongo.mor
import nbcp.base.comm.ApiResult
import nbcp.base.comm.JsonResult
import nbcp.base.comm.ListResult
import nbcp.base.comm.PagerModel
import nbcp.myoql.db.mongo.query
import nbcp.myoql.db.mongo.queryById
import nbcp.myoql.db.mongo.update
import nbcp.myoql.db.mongo.updateById
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

/**
 * 相册列表 内部  CRUD
 */
@RestController
@RequestMapping("/wxAppUser")
class shopUserController {
    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }

    /**
     * 显示shopUser  包含normal  platform  所有
     */
    @PostMapping("/list")
    fun list(
        junior: String?,
        keywords: String?,
        platform: UserPartnerTypeEnum?,
        @org.springframework.web.bind.annotation.RequestBody query: PagerModel<Any?>,
    ): ListResult<WxAppUser> {

        return mor.wx.wxAppUser.query()
                .whereIf(!keywords.isNullOrEmpty()) {
                    it.name mongoLike keywords!!
                }
                .whereIf(platform != null) {
                    it.partnerType mongoEquals platform!!
                }
                .where { it.name mongoNotEquals "" }    //默认查询name 不为 "" 不然看起来太难看了
                .withPager(query)
                .orderByDesc { it.createAt }
                .toListResult()
    }

    data class UserDetailInfo(
            var userInfo: WxAppUser = WxAppUser(),
            var superior1: OpenIdNameUrl = OpenIdNameUrl(),
            var superior2: OpenIdNameUrl = OpenIdNameUrl(),
            var juniorList: MutableList<OpenIdNameUrl> = mutableListOf()
    )

    @PostMapping("/detailById")
    fun detail(id: String): ApiResult<UserDetailInfo> {
        if (id.isEmpty()) return ApiResult.error("非法")

        val userData = UserDetailInfo()

        mor.wx.wxAppUser.queryById(id).toEntity().apply {
            if (this == null) return ApiResult.error("找不到数据")

            userData.userInfo = this
            userData.superior1 = this.superior

            //根据上级级合伙人的openid 查询二级合伙人
            userData.superior2 = getSuperiorByOpenId(this.superior.openid)
            //根据本人openid  查询下级合伙人列表
            userData.juniorList = getJuniorListByOpenId(this.wxUserInfo.openid)
        }

        return ApiResult.of(userData)
    }

    //根据openid 查询上级合伙人信息
    fun getSuperiorByOpenId(openId: String): OpenIdNameUrl {

        if (openId == "") {
            return OpenIdNameUrl()
        }

        val wxAppUser = mor.wx.wxAppUser.query().where { it.wxUserInfo.openid mongoEquals openId }.toEntity()!!

        return wxAppUser.superior
    }

    //根据openId  查询下级列表
    fun getJuniorListByOpenId(openId: String): MutableList<OpenIdNameUrl> {

        val list = mutableListOf<OpenIdNameUrl>()

        mor.wx.wxAppUser.query()
                .where { it.superior.openid mongoEquals openId }
                .toList().apply {
                    ifEmpty { return mutableListOf() }
                    this.forEach { list.add(OpenIdNameUrl(it.wxUserInfo.openid, it.name, it.wxUserInfo.logoUrl)) }
                }

        return list
    }

    @PostMapping("/detailByWxOpenId")
    fun detailByWxOpenId(id: String): ApiResult<WxAppUser> {
        if (id.isEmpty()) return ApiResult.error("非法")

        mor.wx.wxAppUser.query()
                .where { it.wxUserInfo.openid mongoEquals id }
                .toEntity().apply {
                    if (this == null) return ApiResult.error("找不到数据")
                    return ApiResult.of(this)
                }
    }

    @PostMapping("/changeType")
    fun changeType(
            id: String,
            type: UserPartnerTypeEnum?
    ): ApiResult<WxAppUser> {
        if (id.isEmpty()) return ApiResult.error("非法")

        mor.wx.wxAppUser.update()
                .where { it.wxUserInfo.openid mongoEquals id }
                .apply {
                    if (type == UserPartnerTypeEnum.Normal) {
                        val commission = mor.shop.partnerConfig.query().where { it.type mongoEquals UserPartnerTypeEnum.Platform }.toEntity()!!.commission
                        this.set { it.partnerType to UserPartnerTypeEnum.Platform }
                        this.set { it.commission to commission }
                    } else if (type == null || type == UserPartnerTypeEnum.Platform) {
                        val commission = mor.shop.partnerConfig.query().where { it.type mongoEquals UserPartnerTypeEnum.Normal }.toEntity()!!.commission
                        this.set { it.partnerType to UserPartnerTypeEnum.Normal }
                        this.set { it.commission to commission }
                    }
                }.exec()

        return ApiResult.of(mor.wx.wxAppUser.query()
                .where { it.wxUserInfo.openid mongoEquals id }
                .toEntity()!!)
    }

    @PostMapping("/setAdmin")
    fun setAdmin(
            id: String,
            admin: Boolean
    ): JsonResult {

        mor.wx.wxAppUser.update()
                .where { it.wxUserInfo.openid mongoEquals id }
                .unset { it.commission }
                .apply {
                    if (admin) {
                        this.set { it.partnerType to UserPartnerTypeEnum.Admin }
                    } else {
                        this.unset { it.partnerType }
                    }
                }
                .exec()

        return JsonResult()
    }

    @PostMapping("/setStatus")
    fun setStatus(id: String, status: Boolean): JsonResult {
        if (id.isEmpty()) return JsonResult.error("非法")

        //锁定账户
        mor.wx.wxAppUser.updateById(id).set {
            it.isLocked to status
        }.exec()

        mor.wx.wxAppUser.queryById(id).toEntity()!!.wxUserInfo.openid

        //锁定余额
        mor.finance.sysMoney.update()
                .where { it.createBy.openid mongoEquals mor.wx.wxAppUser.queryById(id).toEntity()!!.wxUserInfo.openid }
                .set { it.flag to true }
                .exec()

        return JsonResult();
    }

}
